package com.atguigu.crowd.mvc.interceptor;

import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.exception.LoginFailedException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//拦截器，拦截在spring-web-mvc.xml配置中排除外的所有请求
public class LoginInterceptor extends HandlerInterceptorAdapter {
//    拦截在执行handle方法前，先判断有没有登入
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        如果登入了，Session中会保存登入信息。
        Admin admin = (Admin) request.getSession().getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);
        if(admin == null){
//            没有登入抛异常，这里抛出去会被异常映射捕获CrowdExceptionResolver
            throw new LoginFailedException(CrowdConstant.MESSAGE_ACCESS_FORBIDEN);
        }
        return true;
    }
}
